@file:OptIn(ExperimentalAnimationApi::class)

package com.ljj.bitetime.ui.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.lazy.staggeredgrid.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowForward
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.LocationOn
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DrawerState
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.lifecycle.lifecycleScope
import coil.ImageLoader
import coil.compose.SubcomposeAsyncImage
import coil.request.CachePolicy
import coil.request.ImageRequest
import com.ljj.bitetime.R
import com.ljj.bitetime.data.MockData
import com.ljj.bitetime.item.Shop
import com.ljj.bitetime.ui.theme.BiteTimeTheme
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.Locale

class MainActivity : ComponentActivity() {
    private val context = this
    private lateinit var shops: List<Shop>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        preload()
        setContent {
            BiteTimeTheme {
                Main(shops)
            }
        }
    }

    private fun preload() {
        shops = MockData.shops
        val imageLoader = ImageLoader.Builder(this)
            .memoryCachePolicy(CachePolicy.ENABLED)
            .diskCachePolicy(CachePolicy.ENABLED)
            .build()
        lifecycleScope.launch(Dispatchers.IO) {
            for (shop in shops) {
                val request = ImageRequest.Builder(this@MainActivity)
                    .data(shop.imageRes)
                    .build()
                imageLoader.enqueue(request)
            }
        }
    }

    // 总入口
    @Composable
    fun Main(shops: List<Shop>) {
        val drawerState = rememberDrawerState(DrawerValue.Closed)
        var previousScreen by remember { mutableStateOf<BottomNavItem>(BottomNavItem.Home) }
        var currentScreen by remember { mutableStateOf<BottomNavItem>(BottomNavItem.Home) }
        val navItems = BottomNavItem.items
        LaunchedEffect(currentScreen) {
            previousScreen = currentScreen
        }
        Menu(drawerState) {
            Scaffold(
                bottomBar = {
                    NavigationBar(
                        containerColor = MaterialTheme.colorScheme.surface
                    ) {
                        navItems.forEach { item ->
                            NavigationBarItem(
                                icon = { item.icon() },
                                label = { Text(item.label) },
                                selected = currentScreen == item,
                                onClick = { currentScreen = item },
                                colors = NavigationBarItemDefaults.colors(
                                    indicatorColor = MaterialTheme.colorScheme.primary,
                                    selectedIconColor = MaterialTheme.colorScheme.surface,
                                    selectedTextColor = MaterialTheme.colorScheme.primary,
                                )
                            )
                        }
                    }
                }
            ) { innerPadding ->
                Box(modifier = Modifier.padding(innerPadding)) {
                    AnimatedContent(
                        targetState = currentScreen,
                        transitionSpec = {
                            val previousIndex = BottomNavItem.items.indexOf(previousScreen)
                            val currentIndex = BottomNavItem.items.indexOf(targetState)
                            val direction = if (currentIndex > previousIndex) 1 else -1
                            slideInHorizontally(tween(150)) { width -> direction * width } togetherWith
                                    slideOutHorizontally(tween(150)) { width -> -direction * width }
                        }
                    ) { screen ->
                        when (screen) {
                            BottomNavItem.Home -> Home(shops)
                            BottomNavItem.User -> User()
                        }
                    }
                }
            }
        }
    }

    // 抽屉菜单
    @SuppressLint("ConfigurationScreenWidthHeight")
    @Composable
    fun Menu(
        drawerState: DrawerState,
        content: @Composable () -> Unit
    ) {
        val configuration = LocalConfiguration.current
        val drawerWidth = configuration.screenWidthDp.dp * 0.75f
        ModalNavigationDrawer(
            drawerState = drawerState,
            drawerContent = {
                ModalDrawerSheet(
                    modifier = Modifier.width(drawerWidth)
                ) {
                    Text(
                        text = "菜单",
                        style = MaterialTheme.typography.headlineSmall,
                        modifier = Modifier.padding(10.dp)
                    )
                    HorizontalDivider()
                    NavigationDrawerItem(
                        label = { Text(text = "设置") },
                        selected = false,
                        onClick = {
                            val intent = Intent(context, SettingActivity::class.java)
                            context.startActivity(intent)
                        }
                    )
                    NavigationDrawerItem(
                        label = { Text(text = "关于") },
                        selected = false,
                        onClick = {
                            val intent = Intent(context, AboutActivity::class.java)
                            context.startActivity(intent)
                        }
                    )
                }
            }
        ) {
            content()
        }
    }

    // 主页内容
    @Composable
    fun Home(shops: List<Shop>) {
        Surface(
            modifier = Modifier.fillMaxSize(),
            color = MaterialTheme.colorScheme.background
        ) {
            ConstraintLayout {
                val (title, shopBox) = createRefs()
                // 标题区域
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .fillMaxHeight(0.2f)
                        .padding(10.dp)
                        .constrainAs(title) {
                            centerHorizontallyTo(parent)
                            top.linkTo(parent.top)
                        }
                ) {
                    Text(
                        text = "BITETIME",
                        color = MaterialTheme.colorScheme.primary,
                        style = MaterialTheme.typography.headlineMedium,
                        modifier = Modifier.align(Alignment.Center)
                    )
                }
                // 店铺区域
                Surface(
                    modifier = Modifier
                        .fillMaxWidth()
                        .fillMaxHeight(0.8f)
                        .padding(10.dp)
                        .constrainAs(shopBox) {
                            centerHorizontallyTo(parent)
                            bottom.linkTo(parent.bottom)
                        },
                    shape = RoundedCornerShape(16.dp),
                    color = MaterialTheme.colorScheme.surface,
                    tonalElevation = 4.dp
                ) {
                    LazyVerticalStaggeredGrid(
                        columns = StaggeredGridCells.Fixed(2),
                        modifier = Modifier.fillMaxSize(),
                        verticalItemSpacing = 8.dp,
                        horizontalArrangement = Arrangement.spacedBy(8.dp),
                        contentPadding = PaddingValues(8.dp)
                    ) {
                        items(
                            items = shops,
                            key = { it.id },
                            contentType = { "shop_card" },
                        ) { shop ->
                            ShopCard(shop = shop)
                        }
                    }
                }
            }
        }
    }

    @Composable
    fun User() {
        Surface(
            modifier = Modifier.fillMaxSize(),
            color = MaterialTheme.colorScheme.background
        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(16.dp)
            ) {
                // 用户头像和基本信息
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 16.dp),
                    elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
                    colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
                ) {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        SubcomposeAsyncImage(
                            model = ImageRequest.Builder(context)
                                .data("https://foruda.gitee.com/avatar/1748790154249206542/15816819_ljj2987145363_1748790154.png!avatar200")
                                .crossfade(true)
                                .build(),
                            loading = {
                                Box(
                                    modifier = Modifier
                                        .size(100.dp)
                                        .padding(8.dp),
                                    contentAlignment = Alignment.Center
                                ) {
                                    CircularProgressIndicator()
                                }
                            },
                            error = {
                                Icon(
                                    imageVector = Icons.Default.AccountCircle,
                                    contentDescription = "用户头像",
                                    modifier = Modifier
                                        .size(100.dp)
                                        .padding(8.dp),
                                    tint = MaterialTheme.colorScheme.primary
                                )
                            },
                            contentDescription = "用户头像",
                            modifier = Modifier
                                .size(100.dp)
                                .padding(8.dp)
                                .clip(CircleShape)
                        )
                        Column {
                            Text(
                                text = stringResource(id = R.string.author),
                                style = MaterialTheme.typography.headlineSmall,
                                fontWeight = FontWeight.Bold
                            )
                        }
                    }
                }
                // 功能选项列表
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 16.dp),
                    elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
                    colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
                ) {
                    Column {
                        UserMenuItem(
                            icon = Icons.Default.Menu,
                            title = "我的订单",
                            description = "查看历史订单",
                            onClick = {
                                val intent = Intent(context, OrderActivity::class.java)
                                context.startActivity(intent)
                            }
                        )
                        HorizontalDivider()
                        UserMenuItem(
                            icon = Icons.Default.Favorite,
                            title = "我的收藏",
                            description = "查看收藏的店铺",
                            onClick = {
                                val intent = Intent(context, FavoriteActivity::class.java)
                                context.startActivity(intent)
                            }
                        )
                        HorizontalDivider()
                        UserMenuItem(
                            icon = Icons.Default.LocationOn,
                            title = "地址管理",
                            description = "管理收货地址",
                            onClick = {
                                val intent = Intent(context, AddressActivity::class.java)
                                context.startActivity(intent)
                            }
                        )
                    }
                }
            }
        }
    }

    @Composable
    fun UserMenuItem(
        icon: ImageVector,
        title: String,
        description: String,
        onClick: () -> Unit = {}
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .clickable { onClick() }
                .padding(12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                imageVector = icon,
                contentDescription = null,
                modifier = Modifier
                    .size(36.dp)
                    .padding(end = 12.dp),
                tint = MaterialTheme.colorScheme.primary
            )
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = title,
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Medium
                )
                Text(
                    text = description,
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
            Icon(
                imageVector = Icons.AutoMirrored.Filled.ArrowForward,
                contentDescription = "前往",
                tint = MaterialTheme.colorScheme.outline
            )
        }
    }
}

/**
 * 底部导航项密封类
 * @param label 显示的文字标签
 * @param icon 显示的图标
 */
sealed class BottomNavItem(val label: String, val icon: @Composable () -> Unit) {
    companion object {
        val items: List<BottomNavItem> by lazy {
            listOf(Home, User)
        }
    }
    data object Home : BottomNavItem("首页", { Icon(Icons.Default.Home, contentDescription = null) })
    data object User : BottomNavItem("我的", { Icon(Icons.Default.AccountCircle, contentDescription = null) })

}

@Composable
fun ShopCard(shop: Shop) {
    val context = LocalContext.current
    val roundedCornerShape = RoundedCornerShape(12.dp)
    Card(
        modifier = Modifier
            .fillMaxWidth(0.5f)
            .padding(10.dp)
            .shadow(
                elevation = 1.dp,
                shape = roundedCornerShape
            )
            .clip(roundedCornerShape)
            .clickable {
                val intent = Intent(context, ShopActivity::class.java)
                intent.putExtra("shop", shop)
                context.startActivity(intent)
            },
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.background)
    ) {
        Column(
            modifier = Modifier.padding(10.dp)
        ) {
            // 店铺名称
            Text(
                text = shop.name,
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Bold,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis,
                modifier = Modifier.padding(bottom = 10.dp)
            )
            // 评分信息
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.padding(bottom = 10.dp)
            ) {
                Text(
                    text = String.format(Locale.getDefault(), "%.1f分", shop.rating),
                    style = MaterialTheme.typography.bodyLarge,
                    color = MaterialTheme.colorScheme.secondary
                )
            }
            // 店铺图片
            SubcomposeAsyncImage(
                model = ImageRequest.Builder(context)
                    .data(shop.imageRes)
                    .crossfade(true)
                    .build(),
                loading = {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .aspectRatio(1f)
                            .background(MaterialTheme.colorScheme.surface),
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            painter = painterResource(R.drawable.image_placeholder),
                            contentDescription = "加载中",
                            tint = MaterialTheme.colorScheme.onSurface,
                            modifier = Modifier.size(24.dp)
                        )
                    }
                },
                error = {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .aspectRatio(1f)
                            .background(MaterialTheme.colorScheme.surface),
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            painter = painterResource(R.drawable.image_placeholder),
                            contentDescription = "加载中",
                            tint = MaterialTheme.colorScheme.onSurface,
                            modifier = Modifier.size(24.dp)
                        )
                    }
                },
                contentDescription = "${shop.name}图标",
                modifier = Modifier
                    .fillMaxWidth()
                    .clip(RoundedCornerShape(8.dp)),
                contentScale = ContentScale.FillWidth
            )
        }
    }
}